package com.bbzn.device.client.controller;

import com.bbzn.device.client.constant.ProductConstant;
import com.bbzn.device.client.dto.api.ct.response.ResponseCreateProduct;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.*;
import com.bbzn.device.client.vo.req.DeviceCategoryVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.constant.CwtingConstant;
import com.bbzn.device.client.constant.DeviceConstant;
import com.bbzn.device.client.constant.RedisConstant;
import com.bbzn.device.client.dataobject.DeviceCategory;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dto.api.ct.request.CreateProductResult;
import com.bbzn.device.client.dto.api.ct.request.RequestCreateProduct;
import com.bbzn.device.client.dto.api.ct.response.ResponseBase;
import com.bbzn.device.client.dto.device.DeviceCategoryDTO;
import com.bbzn.device.client.dto.device.DeviceDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.ctg.ag.sdk.biz.aep_product_management.CreateProductResponse;
import com.ctg.ag.sdk.biz.aep_product_management.DeleteProductResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/deviceCategory")
@Slf4j
//@CrossOrigin
/**
 * 设备类目管理
 */
public class DeviceCategoryController extends BaseApiService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private DeviceCategoryService deviceCategoryService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ProductManagementService productManagementService;


    /**
     * 获取对应产品的设备类目列表+条件查询
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDeviceCategoryList", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询对应产品的设备类目列表+条件查询")
    public BaseResponse getDeviceCategoryList(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getProductId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceCategoryDTO dto = new DeviceCategoryDTO();
        dto.setProductId(reqVO.getProductId());
        if (OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            dto.setType(reqVO.getType());
        }
        if (null != reqVO.getPageNum()) {
            dto.setPageNum(reqVO.getPageNum());
        }
        if (null != reqVO.getPageSize()) {
            dto.setPageSize(reqVO.getPageSize());
        }
        dto.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());
        List<Long> ids = commonService.getUserIds(userId);
        dto.setIds(ids);
        PageInfo<DeviceCategory> devices = deviceCategoryService.selectPageByAll(dto);
        for (DeviceCategory deviceCategory : devices.getResultList()) {
            DeviceDTO device = new DeviceDTO();
            device.setUserId(userId);
            device.setOperatorId(userId);
            device.setDeviceCategoryId(deviceCategory.getId());
            int deviceCount = deviceService.findDevCategoryByDeviceCount(device); //COUNT没有去重
            deviceCategory.setDeviceCount(deviceCount);
            device.setUsed(3);
            int bingsCount = deviceService.findCountByAll(device);
            deviceCategory.setBingsCount(bingsCount);
        }
        systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_QUERY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), devices);
    }

    /**
     * 查询设备类目sku
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getDeviceCategorySku", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询设备类目sku")
    public BaseResponse getDeviceCategorySku(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(userId).isPresent()) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceCategory deviceCategory = deviceCategoryService.selectByPrimaryKey(reqVO.getId());
        return setResultSuccess(deviceCategory);
    }

    /**
     * 添加NB设备类目
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addNbDeviceCategory", method = RequestMethod.POST)
    @OperationAnnotation(content = "添加NB设备类目")
    public BaseResponse addNbDeviceCategory(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getAccessType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getProductType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getSecondaryType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getThirdType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getDeviceModel()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getTupDeviceModel()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 参数只传 产品名称，产品描述，一二三级分类 / 其他参数先默认，后续在调整
        // 透传和非透传存在很大区别，省电模式DRX+eDRX 消息可以即刻到达

        // 【1.产品名称. 2. 产品分类】
        // 【3】. 节点类型（必填）：1.设备 ，2.网关（只支持1）
        if (!OptionalBean.ofNullable(reqVO.getNodeType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_NODE_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【4】. 接入类型（必填）: 1.设备直连，2.网关接入，3.南向云接入
        if (!OptionalBean.ofNullable(reqVO.getAccessType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ACCESS_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【5】. 网络类型（必填）:1.WIFI,2.移动蜂窝数据3.NB-IoT,4.以太网,5.蓝牙,6.ZigBee
        if (!OptionalBean.ofNullable(reqVO.getNetworkType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_NETWORK_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【6】. 通讯协议-产品协议（必填）：只支持 1.T-LINK协议 2.MQTT协议 3.LWM2M协议 5.HTTP协议 6.JT/T808 7.TCP协议 10.网关MQTT协议 (只填3)
        if (!OptionalBean.ofNullable(reqVO.getProductProtocol()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PRODUCTPROTOCOL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 一下只对LWM2M协议参数做了校验
        // 【7】. 数据加密方式 1:sm1,2:sm2,3:sm4,4:dtls,5:明文（只支持MQTT/LWM2M/TCP）
        if (!OptionalBean.ofNullable(reqVO.getDataEncryption()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_DATAENCRYPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 【8】. 认证方式 1:特征串认证,2:SM9认证,3:证书认证,4:IMEI认证，5:SIMID认证，6:SM2认证，7:IPV6标识认证
        if (!OptionalBean.ofNullable(reqVO.getAuthType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_AUTH_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        // 【9】. Endpoint格式（LWM2M协议必填）:1.IMEI 2.URN:IMEI:###############3.URN:IMEI
        if (!OptionalBean.ofNullable(reqVO.getEndpointFormat()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_ENDPOINT_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【10】. 设备型号 设备直连并且非JT/T808协议产品必填
        if (!OptionalBean.ofNullable(reqVO.getTupDeviceModel()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_TUPDEVICEMODEL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【11】. 是否透传：0.透传，1不透传（JT/T808，只有透传，消息格式必须只能传null）
        if (!OptionalBean.ofNullable(reqVO.getTupIsThrough()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_TUPISTHROUGH_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 不透传
        if (reqVO.getTupIsThrough() == 1) {
            if (!OptionalBean.ofNullable(reqVO.getPayloadFormat()).isPresent()) {
                systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PAYLOADFORMAT_PREFIX + language);
                throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
            }
        }

        //【12】. 省电模式（LWM2M协议必填）：1.PSM 2.DRX 3.eDRX
        if (!OptionalBean.ofNullable(reqVO.getPowerModel()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_POWERMODEL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        // 【13】. eDRX模式时间窗(LWM2M协议,当省电模式为3时,必填):20 ～ 10485.76 间的值
        if (reqVO.getPowerModel() == 3) {
            if (!OptionalBean.ofNullable(reqVO.getLwm2mEdrxTime()).isPresent()) {
                systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_LWM2MEDRXTIME_PREFIX + language);
                throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
            }
        }
        //【14】. 是否已有电信官方认证通过的profile
        if (!OptionalBean.ofNullable(reqVO.getProfile()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ProductConstant.PRODUCT_ENUM, ProductConstant.PRO_NO_PROFILE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        reqVO.setEncryptionType(0);
        reqVO.setProductName(reqVO.getName());
        reqVO.setTupIsProfile(1);
        RequestCreateProduct requestCreateProduct = BabaBeanUtils.voToDto(reqVO, RequestCreateProduct.class);
//        RequestCreateProduct requestCreateProduct = new RequestCreateProduct();
//        requestCreateProduct.setProductName("NB_调试_46666");
//        requestCreateProduct.setProductType("智慧城市");
//        requestCreateProduct.setSecondaryType("消防安全");
//        requestCreateProduct.setThirdType("工业用烟雾报警器");
//        requestCreateProduct.setEncryptionType(0);
//        requestCreateProduct.setNodeType(1);
//        requestCreateProduct.setAccessType(1);
//        requestCreateProduct.setIsFollowTeleNorm(1);
//        requestCreateProduct.setNetworkType(3);
//        requestCreateProduct.setProductProtocol(3);
//        requestCreateProduct.setAuthType(4);
//        requestCreateProduct.setEndpointFormat(1);
//        requestCreateProduct.setPowerModel(2);
//        requestCreateProduct.setPayloadFormat(1);
//        requestCreateProduct.setProductDesc("长怕结果");
//        requestCreateProduct.setTupIsProfile(1);
//        requestCreateProduct.setTupIsThrough(0);
//        requestCreateProduct.setDataEncryption(5);
//        requestCreateProduct.setTupDeviceModel("NB_调试_4444");

//        byte[] body = JSON.toJSONString(requestCreateProduct).getBytes();
//        Map<String, String> map = (Map<String, String>)JSON.toJSON(requestCreateProduct);
//
//        Map<String, Object> headerMap=new HashMap<>();
//        headerMap.put("application","6Ca557eysj7");
////        headerMap.put("","");
////        headerMap.put("","");
////        headerMap.put("","");
//        String postUrl= "https://dm.ctwing.cn/dm/product/v1/addProductInfo";

//       HttpUtils.doPostForm(postUrl,map);

        CreateProductResponse createProductResponse = productManagementService.createProduct(requestCreateProduct);
        // 4.响应结果
        int code = createProductResponse.getStatusCode();
        if (code != 200) {
            throw new DefinitException(code, createProductResponse.getMessage());
        }
        byte[] retBody = createProductResponse.getBody();
        System.out.println(retBody);
        ResponseCreateProduct responseCreateProduct = JsonUtils.byteToJaveBean(retBody, ResponseCreateProduct.class);
        Integer resCode = responseCreateProduct.getCode();
        if (resCode != 0) {
            throw new DefinitException(resCode, responseCreateProduct.getMsg());
        }
        CreateProductResult createProductResult = responseCreateProduct.getResult();
        Long productId = createProductResult.getProductId().longValue();

        // 保存产品信息 [图片地址，主键id,产品名称，产品描述，创建时间，创建人，APIKey等]
        DeviceCategory deviceCategory = new DeviceCategory();
        if (OptionalBean.ofNullable(productId).isPresent()) {
            deviceCategory.setNbProductId(productId);
        }
        if (!OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVNAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getProductId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_PROID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_UN_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getImgUrl()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMGURL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getDevFunctions()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVFUNCTIONS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        deviceCategory.setType(reqVO.getType());
        deviceCategory.setName(reqVO.getName());
        deviceCategory.setImgUrl(reqVO.getImgUrl());
        deviceCategory.setUpdateTime(new Date());
        deviceCategory.setCreateTime(new Date());
        deviceCategory.setProductId(reqVO.getProductId());
        deviceCategory.setStatus(1);
        // 产品类型 0:非NB / 1NB
        deviceCategory.setProType(1);
        if (OptionalBean.ofNullable(reqVO.getRemark()).isPresent()) {
            deviceCategory.setRemark(reqVO.getRemark());
        }
        // 产品API key
        deviceCategory.setMasterKey(createProductResult.getApiKey());
        // 产品协议
        deviceCategory.setProductProtocol(reqVO.getProductProtocol());
        // 是否透传
        deviceCategory.setTupisThrough(reqVO.getTupisThrough());
        // lwm2m协议有profile
        if (reqVO.getProductProtocol() == 3 && reqVO.getProfile() == 1) {
            // 指令下发接口
            deviceCategory.setOrderSendStrategy(CwtingConstant.LWM2M_PROFILE);
        } else {
            deviceCategory.setOrderSendStrategy(CwtingConstant.OTHER_UNIFY);
        }
        if (OptionalBean.ofNullable(reqVO.getBomUrl()).isPresent()) {
            deviceCategory.setBomUrl(reqVO.getBomUrl());
        }
        if (reqVO.getSku() != null) {
            deviceCategory.setSku(reqVO.getSku());
        }
        deviceCategory.setDevFunctions(reqVO.getDevFunctions());
        DeviceCategoryDTO dto = new DeviceCategoryDTO();
        BeanUtils.copyProperties(deviceCategory, dto);
        int count = deviceCategoryService.findCountByAll(dto);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_ANAGIN_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        deviceCategoryService.insertSelective(deviceCategory);
        systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_INSERT_SUCCESS_PREFIX + "CN");
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 添加非NB设备类目
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addDeviceCategory", method = RequestMethod.POST)
    @OperationAnnotation(content = "添加非NB设备类目")
    public BaseResponse addDevice(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVNAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getProductId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_PROID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_UN_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getImgUrl()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMGURL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getDevFunctions()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVFUNCTIONS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceCategory deviceCategory = new DeviceCategory();
        deviceCategory.setProType(0);
        deviceCategory.setType(reqVO.getType());
        deviceCategory.setName(reqVO.getName());
        deviceCategory.setImgUrl(reqVO.getImgUrl());
        deviceCategory.setUpdateTime(new Date());
        deviceCategory.setCreateTime(new Date());
        deviceCategory.setProductId(reqVO.getProductId());
        deviceCategory.setStatus(1);
        if (OptionalBean.ofNullable(reqVO.getRemark()).isPresent()) {
            deviceCategory.setRemark(reqVO.getRemark());
        }
        if (OptionalBean.ofNullable(reqVO.getBomUrl()).isPresent()) {
            deviceCategory.setBomUrl(reqVO.getBomUrl());
        }
        if (reqVO.getSku() != null) {
            deviceCategory.setSku(reqVO.getSku());
        }
        /*if (StringUtils.isNotEmpty(reqVO.getSku())){
            deviceCategory.setSku(JSONArray.parseArray(reqVO.getSku()));
        }*/
        deviceCategory.setDevFunctions(reqVO.getDevFunctions());

        DeviceCategoryDTO dto = new DeviceCategoryDTO();
        BeanUtils.copyProperties(deviceCategory, dto);
        int count = deviceCategoryService.findCountByAll(dto);
        if (count > 0) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_ANAGIN_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        deviceCategoryService.insertSelective(deviceCategory);
        systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_INSERT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 更新设备类目
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateDeviceCategory", method = RequestMethod.POST)
    @OperationAnnotation(content = "更新设备类目")
    public BaseResponse updateDeviceCategory(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getName()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVNAME_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_UN_TYPE_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getImgUrl()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_IMGURL_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(reqVO.getDevFunctions()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_DEVFUNCTIONS_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceCategory deviceCategory = new DeviceCategory();
        deviceCategory.setId(reqVO.getId());
        deviceCategory.setType(reqVO.getType());
        deviceCategory.setName(reqVO.getName());
        deviceCategory.setUpdateTime(new Date());
        deviceCategory.setImgUrl(reqVO.getImgUrl());
        deviceCategory.setBomUrl(reqVO.getBomUrl());
        if (OptionalBean.ofNullable(reqVO.getRemark()).isPresent()) {
            deviceCategory.setRemark(reqVO.getRemark());
        }
        if (null != reqVO.getSku()) {
            deviceCategory.setSku(reqVO.getSku());
        }
        deviceCategory.setDevFunctions(reqVO.getDevFunctions());
        deviceCategoryService.updateByPrimaryKeySelective(deviceCategory);
        systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_UPDATE_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 删除设备类目
     *
     * @param reqVO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delDeviceCategory", method = RequestMethod.POST)
    @OperationAnnotation(content = "删除设备类目")
    public BaseResponse delDeviceCategory(@RequestBody DeviceCategoryVO reqVO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        if (null == reqVO.getId() || 0 == reqVO.getId()) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_NO_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        /*删除类目先判断是否有绑定设备，有则提示解绑*/
        DeviceDTO deviceDTO = new DeviceDTO();
        deviceDTO.setDeviceCategoryId(reqVO.getId());
        int result = deviceService.findCountByAll(deviceDTO);
        if (result > 0) {
            systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_CATEGORYID_EXIST_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        DeviceCategory deviceCategory = deviceCategoryService.selectByPrimaryKey(reqVO.getId());
        delNbDevice(deviceCategory);
        systemParam = systemParamByCacheService.getValues(DeviceConstant.DEVICE_ENUM, DeviceConstant.DEVICE_DEL_SUCCESS_PREFIX + language);
        deviceCategoryService.deleteByPrimaryKey(reqVO.getId());
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 调用电信删除NB设备接口
     *
     * @param category
     * @throws Exception
     */
    private void delNbDevice(DeviceCategory category) throws Exception {
        //NB产品
        if(null==category.getProType()){
            return;
        }
        if (category.getProType() == 1) {
            DeleteProductResponse deleteProductResponse = productManagementService.deleteProduct(category.getMasterKey(), category.getNbProductId().intValue());
            // 4.响应结果
            int code = deleteProductResponse.getStatusCode();
            if (code != 200) {
                throw new DefinitException(code, deleteProductResponse.getMessage());
            }
            byte[] retBody = deleteProductResponse.getBody();
            System.out.println(retBody);
            ResponseBase responseBase = JsonUtils.byteToJaveBean(retBody, ResponseBase.class);
            Integer resCode = responseBase.getCode();
            if (resCode != 0) {
                throw new DefinitException(resCode, responseBase.getMsg());
            }
        }
    }

}
